<?php

namespace app\api\controller\v45;

use app\api\controller\v2\Auth;
use app\common\cachemodel\AppMonthFortuneVipUnlockRecord;
use app\common\cachemodel\FortuneRecodeBack;
use app\common\cachemodel\MonthFortune;
use app\common\cachemodel\ZlUserVip;
use app\common\lib\astrolog\FortunesChange;
use app\common\lib\PushQueue;
use app\common\lib\Util;
use app\common\model\AppLogicVersion;
use app\common\model\Orders;
use app\common\model\Recode;
use app\common\model\SystemLogicVersion;
use think\Env;
use think\response\Json;
use XznsTools\cache\CacheManage;

class FortuneForMonth extends Auth
{
    protected $month_id;

    protected $active_switch;

    protected $msg;

    public function _initialize()
    {
        parent::_initialize();

        $this->month_id = config('goods.month_id');
        $this->active_switch = false;
//        $this->active_switch = checktime();
    }

    /**
     * 月运详情
     * @return Json
     * @throws Exception
     */
    public function index()
    {
        $rid = input('param.rid/d', 0);
        $year = input('param.year/d', 0);
        $month = input('param.month/d', 0);
        $this->check_param($rid, $year, $month);
        if ($this->msg)
        {
//            Log::write('v7月运详情请求参数有误：' . $this->msg, 'notice', true);
            return show(config('code.error'), $this->msg);
        }
        $recode = (new Recode())->getRecode(['id' => $rid]);
        if (!$recode || $recode['uid'] != $this->user['id'])
        {
            return show(config('code.error'), '档案不存在');
        }
        //当前查看的时间
        $now_time = strtotime($year . '-' . $month);
        //日历显示时间范围
        $range_start = config('fortune.fortune_time_range')['month']['start'];
        $range_end = config('fortune.fortune_time_range')['month']['end'];

        $OrdersModel = new  Orders();
        //解锁状态
        $unlock_status = 0;
        // 获取已解锁的时间范围
        $unlockMonths = (new MonthFortune())->getReocdeFortuneUnlockMonths($rid);
        $time_range = array_map(function ($timeValue)
        {
            return date('Y-n', strtotime($timeValue));
        }, $unlockMonths);

        //更新逻辑数据定义
        $update_logic = [
            'title' => '',
            'content' => '',
            'status' => 0,
        ];
        $fortune = [
            'underway_fortune' => [],
            'predicted_fortune' => [],
            'completed_fortune' => [],
        ];
        $unlockRecodeInfo = null;
        $isCurrentMonth = $now_time === strtotime(date('Y-m'));
        // 获取 用户vip等级
        $vipLevel = (new ZlUserVip())->getUserVipLevel($this->user['id']);
        if (in_array(date('Y-n', $now_time), $time_range, true))
        {   // 已下单解锁
            $fortuneDetail = (new FortunesChange())->init2($recode, date('Y-m', $now_time));
            $unlock_status = (int)$fortuneDetail['status'];
            //用户计算成功后获取运势信息并查询逻辑版本信息
            if ($unlock_status === 2)
            {
                $fortune['underway_fortune'] = $this->resetFortuneTimeRange(1, $fortuneDetail['fortune']['underway_fortune']);
                $fortune['predicted_fortune'] = $this->resetFortuneTimeRange(2, $fortuneDetail['fortune']['predicted_fortune']);
                $fortune['completed_fortune'] = $this->resetFortuneTimeRange(3, $fortuneDetail['fortune']['completed_fortune']);
                //获取当前最新版本逻辑信息
                $SystemLogicModel = new SystemLogicVersion();
                $logic_data = $SystemLogicModel->getVersion(['type' => 2]);
                //获取当前档案逻辑版本号
                $AppLogicModel = new AppLogicVersion();
                $user_logic = $AppLogicModel->getVersion(['rid' => $rid, 'type' => 2, 'time' => date('Y-m', $now_time)]);

                if ($user_logic)
                {
                    //若查看的时间版本号不是最新,提示更新
                    if ($logic_data['version'] && $user_logic < $logic_data['version'])
                    {
                        $update_logic = [
                            'title' => $logic_data['title'],
                            'content' => $logic_data['content'],
                            'status' => 1,
                        ];
                    }
                } elseif (!$user_logic)
                {
                    $update_logic = [
                        'title' => $logic_data['title'],
                        'content' => $logic_data['content'],
                        'status' => 1,
                    ];
                }

                $unlockRecodeInfo = [
                    'recode_is_change' => $fortuneDetail['recode_is_change'],
                    'info' => (new Util)->getFortuneDetailRecodeInfo([$fortuneDetail['recode_info']], (int)$this->user['rid']),
                    'change_title' => $fortuneDetail['recode_is_change'] ? '检测到档案信息发生修改' : '',
                    'change_desc' => $fortuneDetail['recode_is_change'] ? '已购买的运势内容不会随着档案的修改重新计算' : '',
                    'title' => in_array($fortuneDetail['type'], [3, 4], true) ? '解锁时的档案信息' : '购买时的档案信息',
                    'btn_data' => null,
                ];

                if ($fortuneDetail['recode_is_change'])
                {   // 档案信息修改
                    if ($recode['isself'] && $vipLevel > 0 && $isCurrentMonth && !(new AppMonthFortuneVipUnlockRecord())->monthVipReunlockIsUsed($this->user['id']))
                    {   // 自己的档案 并且 当月 并 未使用会员权益重新计算
                        $unlockRecodeInfo['change_title'] = '检测到当前档案出生时间已发生修改';
                        $unlockRecodeInfo['change_desc'] = '订阅解锁的月运支持修改1次档案，选择新的档案重新计算后旧的月运内容不会被保存。';
                        $unlockRecodeInfo['btn_data'] = [
                            'name' => '重新计算',
                            'type' => 1,
                        ];
                    } else
                    {
                        $unlockRecodeInfo['btn_data'] = [
                            'name' => '再次开通',
                            'type' => 2,
                        ];
                    }
                }
            }
        }

        //统计订单人数
        $fortune_base_num = $unlock_status === 2 ? 0 : $OrdersModel->fortune_base(['type' => 1]);

        if (in_array($unlock_status, [0, 1, 3], true))
        {
            if ($recode['isself'])
            {   // 自己的档案
                $desc = '会员可免费解锁当月运势';
                /**
                 * 未解锁情况
                 * 1、 当月情况 不管是否是vip用户  都显示会员权益
                 * 2、 过去月份情况 都不显示会员权益
                 * 3、 未来月份情况  会员用户 显示会员权益  非会员用户不显示会员权益
                 */
                $boonImg = '/test/fortune/boon_img.png';
                $style = 2;
                switch ($unlock_status)
                {
                    case 0:
                        if ($vipLevel)
                        {   // VIP用户
                            if ($isCurrentMonth)
                            {
                                if ((new AppMonthFortuneVipUnlockRecord())->currentMonthVipUnlockIsUsed($this->user['id']))
                                {   // 本月会员权益已使用
                                    $desc = '本月会员权益已使用（次月权益不变）';
                                    $btnList = [
                                        [
                                            'name' => '购买解锁',
                                            'type' => 1,    // 0=>点击无效果 1=>购买解锁 2=>订阅会员 3=>会员权益解锁
                                            'style' => 1,
                                        ],
                                    ];
                                } else
                                {   // 本月会员权益未使用
                                    $btnList = [
                                        [
                                            'name' => '现在计算',
                                            'type' => 3,    // 0=>点击无效果 1=>购买解锁 2=>订阅会员 3=>会员权益解锁
                                            'style' => 1,
                                        ],
                                    ];
                                }
                            } else
                            {
                                $btnList = [
                                    [
                                        'name' => "购买解锁",
                                        'type' => 1,    // 0=>点击无效果 1=>购买解锁 2=>订阅会员 3=>会员权益解锁
                                        'style' => 1,   // 1=>按钮样式 2=>下划线样式 3=>提示语样式
                                    ],
                                ];
                                if ($now_time > strtotime(date('Y-m')))
                                {
                                    $btnList[] = [
                                        'name' => '当月免费解锁',
                                        'type' => 0,
                                        'style' => 3,
                                    ];
                                }
                            }
                        } else
                        {   // 非VIP用户   未订阅
                            if ($isCurrentMonth)
                            {   // 当前月份
                                $btnList = [
                                    [
                                        'name' => "订阅会员解锁",
                                        'type' => 2,    // 0=>点击无效果 1=>购买解锁 2=>订阅会员 3=>会员权益解锁
                                        'style' => 1,   // 1=>按钮样式 2=>下划线样式 3=>提示语样式
                                    ], [
                                        'name' => '购买解锁',
                                        'type' => 1,
                                        'style' => 2,
                                    ],
                                ];
                            } else
                            {
                                $btnList = [
                                    [
                                        'name' => "购买解锁",
                                        'type' => 1,
                                        'style' => 1,
                                    ],
                                ];
                                if ($now_time > strtotime(date('Y-m')))
                                {
                                    $btnList[] = [
                                        'name' => '订阅会员 当月免费解锁',
                                        'type' => 2,
                                        'style' => 2,
                                    ];
                                }
                                // 未订阅 非VIP用户 不显示权益
                                $boonImg = '';
                            }
                        }
                        break;
                    case 1:
                    case 3:
                        $btnList = [
                            [
                                'name' => '计算中...',
                                'type' => 0,
                                'style' => 1,
                            ],
                        ];
                        break;
                }
                if ($now_time < strtotime(date('Y-m')) || (!$vipLevel && !$isCurrentMonth))
                {   // 过去月份  不管是否订阅 都不显示 会员权益    或者   非VIP用户 切不是当前月份
                    $boonImg = '';
                }
            } else
            {
                switch ($unlock_status)
                {
                    case 0:
                        $btnList = [
                            [
                                'name' => "{$fortune_base_num}人已解锁",
                                'type' => 0,
                                'style' => 3,
                            ], [
                                'name' => '立即解锁',
                                'type' => 1,
                                'style' => 1,
                            ],
                        ];
                        break;
                    case 1:
                    case 3:
                        $btnList = [
                            [
                                'name' => '计算中...',
                                'type' => 0,
                                'style' => 1,
                            ],
                        ];
                        break;
                }

                $style = 1;
            }

            $unlock_tips = [
                'title' => Util::IsHuawei() ? '月度节律报告解锁' : '月度报告解锁',
                'content' => Util::IsHuawei() ? '解锁当前节律报告,可查看你本月会发生什么,并提前七天得到预警,得知对应的方法和建议。' : '解锁当前运势,可查看你本月会发生什么,并提前七天得到预警,得知对应的方法和建议。',
                'desc' => $desc ?? '',
                'btn_list' => $btnList ?? [],
                'boon_img' => $boonImg ?? '',
                'style' => $style,
            ];
        } else
        {
            $unlock_tips = null;
        }

        $data = [
            'time' => $time_range,
            'underway_fortune' => $fortune['underway_fortune'],
            'predicted_fortune' => $fortune['predicted_fortune'],
            'completed_fortune' => $fortune['completed_fortune'],
            'unlock_num' => (int)($fortune_base_num),
            'unlock_status' => $unlock_status,
            'time_range' => [
                'start_time' => $range_start,
                'end_time' => $range_end,
            ],
            'update_logic' => $update_logic,
            'unlock_tips' => $unlock_tips,
            'unlock_recode_info' => $unlockRecodeInfo,
        ];

        // 活动开关，默认关闭
        $config = config('active.fortune_active');
        $data['active_switch'] = [
            'day_active' => [
                'is_open' => false,
                'icon' => '',
                'banner' => '',
                'target' => 'link',
                'link' => Env::get('host.domain') . '/web/fortune_year/active_details',//大礼包h5
            ],
            'month_active' => [
                'is_open' => false,
                'icon' => '',
                'banner' => $config['banner'],
                'target' => 'link',
                'link' => Env::get('host.domain') . '/web/fortune_year/active_details',//大礼包h5
            ],
            'year_active' => [
                'is_open' => false,
                'icon' => $config['icon'],
                'banner' => $config['banner'],
                'target' => 'link',
                'link' => Env::get('host.domain') . '/web/fortune_year/active_details',//大礼包h5
            ],

        ];
        //若未解锁并在活动时间内，开启
        if ($this->active_switch)
        {
            $data['active_switch']['day_active']['is_open'] = false;
            $data['active_switch']['month_active']['is_open'] = true;
            $data['active_switch']['year_active']['is_open'] = true;
        }

        return show(config('code.success'), '加载成功', $data);
    }

    /**
     * 运势时间段处理
     * @param $type
     * @param $fortune
     * @return mixed
     */
    private function resetFortuneTimeRange($type, $fortune)
    {
        foreach ($fortune as $key => $item)
        {
            $start_time = implode('.', array_slice(explode('.', $item['start_time']), 1));
            $end_time = implode('.', array_slice(explode('.', $item['end_time']), 1));
            if ($item['end_days'])
            {
                //预警
                if ($type == 2)
                {
                    $fortune[$key]['time_range_des'] = '将持续' . $item['end_days'] . '天';

                } //进行中
                else
                {
                    $fortune[$key]['time_range_des'] = $item['end_days'] . '天后结束';
                }
            } else
            {
                $fortune[$key]['time_range_des'] = '已结束';
            }
            $fortune[$key]['time_range'] = $start_time . '-' . $end_time;
            unset($fortune[$key]['all_days'], $fortune[$key]['start_days'], $fortune[$key]['end_days'], $fortune[$key]['start_time'], $fortune[$key]['end_time']);
        }
        return $fortune;
    }

    /**
     * 检测运势首页请求参数
     * @param $rid
     * @param $year
     * @param $month
     * @return string
     */
    private function check_param($rid, $year, $month)
    {
        $this->msg = '';
        if (!$rid)
        {
            return $this->msg = '缺少档案';
        }
        if (!$year || !$month)
        {
            return $this->msg = '未知的时间';
        }
        if (!in_array($month, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], true))
        {
            return $this->msg = '缺少月份';
        }
    }

    public function vipUnlock()
    {
        $rid = input('rid/d', 0);
        $year = input('year/d', 0);
        $month = input('month/d', 0);
        $type = input('type/d', 0);
        $this->check_param($rid, $year, $month);
        if ($this->msg)
        {
            return show(config('code.error'), $this->msg);
        }
        if (!in_array($type, [1, 2], true))
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }
        $recode = (new Recode())->getRecode(['id' => $rid]);
        if (!$recode || $recode['uid'] != $this->user['id'])
        {
            return show(config('code.error'), '档案不存在');
        }
        //当前查看的时间
        $now_time = strtotime($year . '-' . $month);
        if ($now_time !== strtotime(date('Y-m')))
        {
            $m = $type === 1 ? '服务异常，只有当月的运势才能计算～' : '服务异常，只有当月的运势才能重新计算～';
            return show(config('code.error'), $m);
        }
        // 获取 用户vip等级
        $vipLevel = (new ZlUserVip())->getUserVipLevel($this->user['id']);
        if (!$vipLevel)
        {
            return show(config('code.error'), '服务异常，只有订阅会员才能计算～');
        }
        // 获取已解锁的时间范围
        $monthFortuneModel = new MonthFortune();
        $unlockMonths = $monthFortuneModel->getReocdeFortuneUnlockMonths($rid);
        $time_range = array_map(function ($timeValue)
        {
            return date('Y-n', strtotime($timeValue));
        }, $unlockMonths);
        $monthYear = date('Y-m', $now_time);
        $cacheKey = $rid . ':' . $monthYear;
        if ($type === 1)
        {   // 会员权益 解锁
            if (in_array($year . '-' . $month, $time_range, true))
            {
                return show(config('code.error'), '服务异常，已经解锁过了～');
            }
            if ((new AppMonthFortuneVipUnlockRecord())->currentMonthVipUnlockIsUsed($this->user['id']))
            {
                return show(config('code.error'), '服务异常，本月会员权益已经使用过了～');
            }
            $recodeData = [
                'id' => $rid,
                'name' => $recode['name'],
                'type' => $recode['type'],
                'year' => $recode['year'],
                'month' => $recode['month'],
                'day' => $recode['day'],
                'hour' => $recode['hour'],
                'minute' => $recode['minute'],
                'timezone' => $recode['timezone'],
                'birth_country' => $recode['birth_country'],
                'birth_province' => $recode['birth_province'],
                'birth_city' => $recode['birth_city'],
                'live_country' => $recode['live_country'],
                'live_province' => $recode['live_province'],
                'live_city' => $recode['live_city'],
                'long_deg' => $recode['long_deg'],
                'long_min' => $recode['long_min'],
                'ew' => $recode['ew'],
                'lat_deg' => $recode['lat_deg'],
                'lat_min' => $recode['lat_min'],
                'ns' => $recode['ns'],
                'avatar' => $recode['avatar'],
                'is_summer' => $recode['is_summer'],
                'uid' => $recode['uid'],
                'isself' => $recode['isself'],
            ];
            $backRid = (new FortuneRecodeBack())->insertGetId(['rid' => $rid, 'recode_info' => \GuzzleHttp\json_encode($recodeData, JSON_UNESCAPED_UNICODE)]);
            $recodeUniqueKey = "{$recode['type']}:{$recode['year']}:{$recode['month']}:{$recode['day']}:{$recode['hour']}:{$recode['minute']}:{$recode['timezone']}:{$recode['ew']}:{$recode['long_deg']}:{$recode['long_min']}:{$recode['ns']}:{$recode['lat_deg']}:{$recode['lat_min']}:{$recode['is_summer']}";
            $resMonthFortune = $monthFortuneModel->batchGetRecodeFortuneMonthInfo($rid, [$monthYear], [$recodeUniqueKey], 0);
            $isUpdate = false;
            if ($resMonthFortune && isset($resMonthFortune[$cacheKey][$recodeUniqueKey]) && $resMonthFortune[$cacheKey][$recodeUniqueKey])
            {
                $monthForData = \GuzzleHttp\json_decode(current($resMonthFortune)[$recodeUniqueKey], true);
                if ($monthForData['type'] == 0)
                {
                    $isUpdate = true;
                }
            }
            if ($isUpdate)
            {
                $updateData = [
                    'type' => 3,
                    'order_id' => '',
                    'is_simpleness' => 0,
                    'status' => 1,  // 解锁状态 0=>未解锁 1=>计算中 2=>计算成功 3=>计算失败
                    'rid_back' => $backRid,
                ];
                $monthFortuneModel->where('id', $monthForData['id'])->update($updateData);
            } else
            {
                $fortuneLockData = [
                    'type' => 3,
                    'is_simpleness' => 0,
                    'order_id' => '',
                    'rid_back' => $backRid,
                    'status' => 1,
                    'rid' => $rid,
                    'month' => $monthYear,
                ];
                $monthFortuneModel->save($fortuneLockData);
            }
            CacheManage::getInstance()->setCacheConfig('fortune.fortune_month')->setCacheKeyDetail('list_v2', $rid . ':' . 0)->rmCache('list_v2');
        } else
        {   // 会员权益 免费重新计算
            if (!in_array($year . '-' . $month, $time_range, true))
            {
                return show(config('code.error'), '服务异常，运势还未解锁～');
            }
            if ((new AppMonthFortuneVipUnlockRecord())->monthVipReunlockIsUsed($this->user['id']))
            {
                return show(config('code.error'), '服务异常，请稍后再试～');
            }
            $recodeData = [
                'id' => $rid,
                'name' => $recode['name'],
                'type' => $recode['type'],
                'year' => $recode['year'],
                'month' => $recode['month'],
                'day' => $recode['day'],
                'hour' => $recode['hour'],
                'minute' => $recode['minute'],
                'timezone' => $recode['timezone'],
                'birth_country' => $recode['birth_country'],
                'birth_province' => $recode['birth_province'],
                'birth_city' => $recode['birth_city'],
                'live_country' => $recode['live_country'],
                'live_province' => $recode['live_province'],
                'live_city' => $recode['live_city'],
                'long_deg' => $recode['long_deg'],
                'long_min' => $recode['long_min'],
                'ew' => $recode['ew'],
                'lat_deg' => $recode['lat_deg'],
                'lat_min' => $recode['lat_min'],
                'ns' => $recode['ns'],
                'avatar' => $recode['avatar'],
                'is_summer' => $recode['is_summer'],
                'uid' => $recode['uid'],
                'isself' => $recode['isself'],
            ];
            $backRid = (new FortuneRecodeBack())->insertGetId(['rid' => $rid, 'recode_info' => \GuzzleHttp\json_encode($recodeData, JSON_UNESCAPED_UNICODE)]);
            $fortuneLockData = [
                'type' => 4,
                'is_simpleness' => 0,
                'order_id' => '',
                'rid_back' => $backRid,
                'status' => 1,
                'rid' => $rid,
                'month' => $monthYear,
            ];
            $monthFortuneModel->save($fortuneLockData);
        }

        CacheManage::getInstance()->setCacheConfig('fortune.fortune_month')->setCacheKeyDetail('details_v2', $cacheKey)->rmCache('details_v2');
        $version = $this->headers['version'] ?? '';
        $odata = [
            'id' => 0,
            'order_id' => '',
            'order_type' => 3,
            'env_type' => 0,
        ];
        (new PushQueue())->fortune_queue($odata, [$recodeData], [$monthYear], $type === 1 ? 3 : 4, $version);

        $insertData = [
            'uid' => $this->user['id'],
            'type' => $type, // 1 => 会员权益解锁 2=>会员权益免费重新计算
            'rid' => $rid,
            'month' => date('Ym', $now_time),
            'create_time' => $this->request->time(),
        ];
        // 写入 权益使用记录
        (new AppMonthFortuneVipUnlockRecord())->SaveData($insertData);

        return show(config('code.success'), '计算成功');
    }
}